<template>
  <div class="details">
    <div class="plus"></div>
    <div class="header">
      <van-nav-bar title="商品详情" left-text="返回" left-arrow @click-left="goBack" />
    </div>
    <div class="body">
      <div class="img">
        <img class="auto-img" :src="productData.large_img" alt="" />
      </div>
      <div class="content">
        <ul>
          <li class="title">
            <div class="left">
              <p>{{ productData.name }}</p>
              <span>{{ productData.enname }}</span>
            </div>
            <div class="right">&yen;{{ productData.price }}</div>
          </li>
          <li class="options">
            <div v-for="(item, index) in productData.rules" :key="index">
              <div class="text">{{ item.title }}</div>
              <ul class="items">
                <li @click="item.active = index2" :class="{ active: index2 === item.active }" v-for="(item2, index2) in item.options" :key="index2">
                  {{ item2.option }}
                </li>
              </ul>
            </div>
          </li>
          <li class="count">
            <div class="left">选择数量</div>
            <div class="right">
              <van-stepper v-model="value" theme="round" button-size="22" disable-input />
            </div>
          </li>
          <li class="describe">
            <p>商品描述</p>
            <div v-for="(item, index) in productData.desc" :key="index">
              {{ index + 1 }}、{{ item }}
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="footer">
      <van-goods-action>
        <van-goods-action-icon ref="badge" icon="bag-o" text="购物袋" :badge="count > 0 ? count : ''" @click="goShopping" :color="count >= 1 ? '#ff5000' : '#646566'" />
        <van-goods-action-icon icon="like-o" :text="collection ? '已收藏' : '收藏'" :color="collection ? '#ff5000' : '#646566'" @click="toggleLike" />
        <van-goods-action-button type="warning" text="加入购物袋" @click="addProduct" />
        <van-goods-action-button type="danger" text="立即购买" @click="goShopping" />
      </van-goods-action>
    </div>
  </div>
</template>





<script>
export default {
  name: "Details",

  data() {
    return {
      pid: "",
      // 商品数量
      value: 1,
      // 购物袋总数量
      count: 0,
      // 收藏状态
      collection: false,
      // 商品数据
      productData: {},
      // 徽章节点
      badgeNode: null,
    };
  },

  created() {
    // 获取商品pid
    this.pid = this.$route.query.pid;
    // 获取商品数据
    this.getProductData();
    // 查询收藏状态
    this.findLike();
    // 查询购物袋状态
    this.getShopbagCount();
  },

  methods: {
    // 跳转到购物车页面
    goShopping() {
      // 设置导航栏当前索引值
      this.$util.setSessionItem("tabbarActive", 2);
      this.$router.replace({ name: "Shopping" });
    },

    // 立即购买
    goPay() {
      
    },

    // 获取商品数据
    getProductData() {
      let pid = this.pid;
      // 查询商品信息
      this.axios({
        method: "get",
        url: "/productDetail",
        params: {
          pid,
        },
      })
        .then((res) => {
          // 
          if (res.data.code === 600) {
            let data = res.data.result[0];
            // 处理商品描述
            data.desc = data.desc.split(/\n/);
            // 处理商品规格
            let rules = ["cream", "milk", "sugar", "tem"];
            let rulesData = [];
            rules.forEach((item) => {
              // 如果商品规格为空则排除
              if (!data[item]) return;
              let rule = {
                title: data[`${item}_desc`],
                active: 0,
                options: [],
              };
              let subRule = data[item].split(/\//);
              subRule.forEach((item) => {
                rule.options.push({ option: item });
              });
              rulesData.push(rule);
            });
            data.rules = rulesData;
            this.productData = data;
          }
        })
        .catch((err) => {
          
        });
    },

    // 查询收藏状态
    findLike() {
      let tokenString = this.$cookies.get("TOKEN");
      // 发起查询收藏状态请求
      this.axios({
        method: "get",
        url: "/findlike",
        params: {
          pid: this.pid,
          // 查看收藏状态需要用户处于登录状态
          tokenString,
        },
      })
        .then((res) => {
          // 
          let data = res.data;
          // 状态码和result有一条数据才算商品已被收藏
          if (data.code === 1000 && data.result.length === 1) {
            //当前商品已经被用户收藏，把收藏状态改为true
            this.collection = true;
          }
        })
        .catch((err) => {
          
        });
    },

    // 查询当前商品购物袋状态
    getShopbagCount() {
      let tokenString = this.$cookies.get("TOKEN");
      this.axios({
        method: "get",
        url: "/shopcartCount",
        params: {
          tokenString,
        },
      })
        .then((res) => {
          // 
          if (res.data.code === 4000) {
            this.count = res.data.result;
          }
        })
        .catch((err) => {
          
        });
    },

    //加入购物袋
    addProduct() {
      let tokenString = this.$cookies.get("TOKEN");
      //获取商品规格
      let rules = this.productData.rules;
      // 处理商品规格
      let selectRule = [];
      rules.forEach((item) => {
        // 提取选项
        selectRule.push(item.options[item.active].option);
      });
      // 发起添加商品请求
      this.axios({
        method: "post",
        url: "/addShopcart",
        data: {
          pid: this.pid,
          count: this.value,
          // 将选项拼接成指定字符串
          rule: selectRule.join("/"),
          tokenString,
        },
      })
        .then((res) => {
          // 
          //用户未登录, 拦截操作, 通知用户去登录
          if (res.data.code == 700) {
            this.$toast("请先登录");
            // 清除token
            this.$cookies.remove("TOKEN");
            // 延迟2秒后跳转到登录页面
            let timer = setTimeout(() => {
              clearTimeout(timer);
              this.$router.replace({ name: "Login" });
            }, 2000);
            return;
          }
          if (res.data.code === 3000) {
            // 修改购物袋显示的数量
            this.count += this.value;
            this.value = 1;
            // 添加类名，执行抖动购物袋的徽章的动画
            if (this.badgeNode === null) {
              // 获取徽章的dom节点
              this.badgeNode = this.$refs.badge.$el.querySelector(".van-info");
            }
            // 
            this.badgeNode.className = "van-info shake";
            // 延迟0.1秒后移除类名
            let timer = setTimeout(() => {
              clearTimeout(timer);
              this.badgeNode.className = "van-info";
            }, 100);
          }
        })
        .catch((err) => {
          
        });
    },

    // 切换收藏状态
    toggleLike() {
      let tokenString = this.$cookies.get("TOKEN");
      //根据collection判断商品是否被收藏
      let url = "";
      if (this.collection) {
        //如果商品已经被收藏, 则执行取消收藏
        url = "/notlike";
      } else {
        url = "/like";
      }
      this.axios({
        method: "POST",
        url,
        //如果是post请求, 参数格式应为 key1=value1&key2=value2...
        data: {
          pid: this.pid,
          tokenString,
        },
      })
        .then((res) => {
          // 
          //用户未登录, 拦截操作, 通知用户去登录
          if (res.data.code == 700) {
            this.$toast("请先登录");
            // 清除token
            this.$cookies.remove("TOKEN");
            // 延迟2秒后跳转到登录页面
            let timer = setTimeout(() => {
              clearTimeout(timer);
              this.$router.replace({ name: "Login" });
            }, 2000);
            return;
          }
          // 提示收藏状态
          this.$toast(res.data.msg);
          // 用户已登录
          if (res.data.code === 800) {
            //收藏商品
            this.collection = true;
            // 用户已收藏
          } else if (res.data.code === 900 && res.data.result === 1) {
            //取消收藏商品，把收藏状态改为false
            this.collection = false;
          }
        })
        .catch((err) => {
          
        });
    },

    // 点击顶部左边按钮返回上一页
    goBack() {
      // 此处有个问题，如果用户从别处跳转过来，那么返回则会返回到用户跳转过来之前的页面
      this.$router.go(-1);
    },
  },
};
</script>





<style lang="less" scoped>
// 抖动购物袋的徽章
/deep/ .shake {
  animation: shake 0.1s linear;
}
@keyframes shake {
  0% {
    top: 0;
  }
  25% {
    top: -4px;
  }
  50% {
    top: 0px;
  }
  75% {
    top: 2px;
  }
  100% {
    top: 0;
  }
}
.van-nav-bar {
  /deep/.van-icon {
    color: #ffa341;
  }
  /deep/.van-nav-bar__text {
    color: #ffa341;
  }
  /deep/.van-nav-bar__title {
    color: #333;
  }
}

.details {
  color: #666;
  .body {
    position: fixed;
    top: 46px;
    bottom: 50px;
    left: 0;
    right: 0;
    overflow-y: auto;
    .img {
      width: 100%;
      height: 280px;
    }
    .content {
      position: absolute;
      top: 250px;
      // bottom: 0;
      left: 0;
      right: 0;
      margin: 0 auto;
      padding: 15px;
      width: 96%;
      // height: auto;
      // height: calc(100% - 250px);
      background-color: #fff;
      border-top-left-radius: 15px;
      border-top-right-radius: 15px;
      box-sizing: border-box;
      .title {
        display: flex;
        .left {
          flex: 1;
          p {
            margin: 0;
            margin-bottom: 5px;
            color: #333;
            font-weight: bold;
            font-size: 18px;
          }
          span {
            color: #999;
          }
        }
        .right {
          padding-top: 3px;
          color: #e4393c;
          font-weight: bold;
          font-size: 16px;
        }
      }
      .options {
        padding: 15px 0;
        font-size: 15px;
        > div {
          display: flex;
          align-items: center;
          padding: 5px 0;
        }
        .text {
          width: 60px;
        }
        .items {
          display: flex;
          font-size: 14px;
          li {
            margin-right: 10px;
            padding: 3px 20px;
            background-color: #eee;
            color: #777;
            border-radius: 26px;
            cursor: pointer;
          }
          .active {
            background-color: #ff594d;
            color: #fff;
          }
        }
      }
      .count {
        display: flex;
        align-items: center;
        padding: 20px 0;
        border-top: 1px solid #ddd;
        border-bottom: 1px solid #ddd;
        .left {
          flex: 1;
        }
      }
      .describe {
        padding-top: 6px;
        div {
          padding: 3px 0;
        }
      }
    }
  }
}
</style>